const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');

var myMap = new Map();

Page({
  data: {

    count:0,
    day_up_count: 0,


    //页面适配
    imgwidth: 0,
    imgheight: 0,
    windowWidth: wx.getSystemInfoSync().screenWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    gift_type:'',//红包类型
    detail_id:'',//红包ID
    feed: {},
   
    goodDaily: null,//每日推荐
    goodsPreSale: null,//新品预告

    //每日上新
    goods_data: {
      list: [],
      page: {
        page_no: 0,
        page_size: 6,
      },
      paginate: {}
    },


    re: [], //推荐活动类型
    acts: [],  //首页货架模板

    //顶部轮播图相关
    carousels: [],   // 轮播图
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 1000,

    //showModalStatus: false,


    //
    isMasked: false,


    //红包相关
    alertpack: false,//弹出红包
    goldisMasked: false,//领取红包
    // alertpack_type:false,
    gift: '0.00',//红包金额
    signContent: '',
    city: null,
    
    //返回顶部
    scrollTop: 0,
    goTop_show: false,
    //网络状态
    nonet:true,
    //加载完显示
    loade:true,

  },



  onLoad: function (options) {
    var that = this;


    myMap.clear()

    console.log("---------- index  onLoad --------")
    console.log("---------- index  onLoad --------")
    console.log(app.globalData.city)

    //获得app_token和安全码security_code
    const data = {
      app_id: app.globalData.app_id,
      private_key: app.globalData.private_key,
    };

    api.getTokenAndCode({
      data,
      success: (res) => {

        console.log(res)
        console.log("======= index.js =================================")
        console.log("---获得app_token和安全码security_code---")
        console.log("app_token:" + res.data.data.app_token)
        console.log("security_code:" + res.data.data.security_code)

        console.log(res)


        if (res.data.rsp_code == 'succ') {

          app.globalData.app_token = res.data.data.app_token;
          app.globalData.security_code = res.data.data.security_code;



          that.gdAppAdvertFind();//获取首页轮播图
          that.getGoodDaily();//每日推荐
          that.getNewProduct();//新品预告
          that.getDayUpte();//每日上新


        } else if (res.data.rsp_code == 'fail') {
          console.log(res.data.error_code)
          console.log(res.data.error_msg)
        }

      }
    })


    //调用地理信息
    //app.getLocation()
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {


    console.log("=============onShow=======================")
    console.log(app.globalData.city)

    this.setData({
      city: app.globalData.city
    })

    //验证用户的user_token
    console.log(app.globalData.memberInfo)
    if (app.globalData.memberInfo != '' && app.globalData.memberInfo!=null){
      //this.userValidate();
    }

    if (app.globalData.hasLogin === true) {
      this.alertred();//弹红包
     }




    //console.log(app.globalData.comeFromPage)

    /* 
        console.log("----------wx.getSetting--------------")
        wx.getSetting({
          success: (res) => {
            console.log(res)
            console.log("---------wx.getSetting---------------")
            console.log(res.data)
          }
          complete: (res) => {
            console.log(res)
            console.log("----------wx.getSetting--------------")
            console.log(res.data)
          }
        })
     */




    /*     console.log("----------wx.openSetting--------------")
        wx.openSetting({
          success: (res) => {
    
            console.log("----------wx.openSetting success--------------")
            console.log(res)
            console.log(res.data)
               
              res.authSetting = {
                "scope.userInfo": true,
                "scope.userLocation": true
              }
            
          }
        }) 

    */
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

    console.log("============onHide========================")
    //app.globalData.comeFromPage = null //使用完，置为空
  },


  //验证用户（判断后台user_token是否发生改变。有改变，说明用户在别的已经终端登陆）
/*   userValidate: function (e) {
    var user_token = app.globalData.memberInfo.user_token;
    const data = {
      user_token: user_token,
      app_token: app.globalData.app_token,
      security_code: app.globalData.security_code
    }

    api.userValidate({
      data,
      success: (res) => {
        console.log(" userValidate  返回 res.data>>>" + res.data);
        var resData = res.data;
        console.log(resData);

        if (resData.rsp_code == 'succ') {
        } else {
          console.log("您在别处已经登陆，被迫下线！");
          wx.showModal({
            title: '温馨提示',
            content: '您已在别处登录，被迫下线!',
            showCancel: false,
            success: function (res) {
              app.userSignOut();
            }
          })
          this.setData({
            alertpack: false,//弹出红包
          })

        }
      },
      fail: (res) => {
        console.log("fail 返回 res.data>>>" + res.data);
      }
    })
  }, */










  //搜索
  getGoodsSearch: function (e) {
    let data = {
      // service: 'psGoods.consumer.freeGetGoodsSearchListPageFind',
      service: 'psGoods.smallprogram.freeGetGoodsSearchListPageFind',
      params: '{"search":"dsdsd"}',
      url_type: 'goods',
      app_token: app.globalData.app_token,
      security_code: app.globalData.security_code
    }

    api.reqData({
      data,
      success: (res) => {
      }
    })
  },


  toDetail: function (e) {
    //根据taobao_link字段的有无判断是淘宝或精品商品
    //再传与后台值的时候 ds:0 表示精品 ds:1表示淘宝
    let ds = e.currentTarget.dataset.hi;
    let goods_id = e.currentTarget.id;
    if ( ds == "huiguo") {
      wx.navigateTo({
        url: `/pages/buy/detail/selfEmployed/selfEmployed?goods_id=` + goods_id,
      });
    } else if (ds == "meitianhui" ){
      wx.navigateTo({
      url: `/pages/buy/detail/selfsupport/selfsupport?goods_id=` + goods_id,
      });
    }
     else {
      wx.navigateTo({
        url: `/pages/buy/detail/taotaoling/taotaoling?goods_id=` + goods_id,
      });
    }

  },


  //每日上新
  getDayUpte() {

    const self = this;

    this.data.day_up_count++;
    console.log("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK 第" + this.data.day_up_count + "请求'每日上新'接口")

    //限制请求次数，防止商品重复
    if (wx.getStorageSync("getDayUpte") == "") {

      //监听网络状态
      if (app.globalData.isConnected){
        wx.setStorageSync("getDayUpte", "getDayUpte")
        self.setData({ nonet: true })

      }else{
         //网络不通的时候，提示一下!
/*         wx.showLoading({
          title: '网络不通',
        })
        setTimeout(function () {
          wx.hideLoading()
        }, 3000) */    
        wx.removeStorageSync("getDayUpte")
        console.log("断网啦++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
        self.setData({ nonet: false })
      }


        let pageData = {
          page_no: this.data.goods_data.page.page_no + 1,
          page_size: this.data.goods_data.page.page_size,
        }

        let data = {
          page: JSON.stringify(pageData),
          //每日上新接口
          // service: 'psGoods.consumer.freeGetGoodsNewestListPageFind',
          //自营商品接口
          service: 'psGoods.smallprogram.freeGetGoodsForOwnListPageFind',
          params: '{}',
          url_type: 'goods',
          app_token: app.globalData.app_token,
          security_code: app.globalData.security_code
        }


        var goods_data = this.data.goods_data
        ////////////////////////////////////////////////////////
        api.reqData({
          data,
          success: (res) => {

            console.log("--------------每日上新------------------------------------")
            //console.log(res)

            //图片地址由https 改为 http
            var goodlist = res.data.data.list

            for (var i = 0; i < goodlist.length; i++) {
              myMap.set(goodlist[i].goods_id, "goods")

              goodlist[i].pic_info_url = goodlist[i].pic_info_url.replace("https", "http")
              goodlist[i].taobao_link = (goodlist[i].taobao_price - goodlist[i].discount_price).toFixed(2);
              goodlist[i].huiguo_link = (goodlist[i].market_price - goodlist[i].discount_price).toFixed(2);
            }

            goods_data.list = [...goods_data.list, ...goodlist]
            goods_data.page.page_no = res.data.data.page.page_no
            goods_data.page.page_size = res.data.data.page.page_size
            //paginate.total_page = res.data.data.page.total_page
            goods_data.paginate.total_count = res.data.data.page.total_count
            //判断hasNext
            if (goods_data.paginate.total_count > goods_data.page.page_no * goods_data.page.page_size) {
              goods_data.paginate.hasNext = true
            } else {
              goods_data.paginate.hasNext = false


            }

            this.data.count++;
            console.log("KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK 后台调用接口 返回数据次数：>>>>  " + this.data.count)
            console.log("已经得到的商品数量： >>>>>>>   " + goods_data.list.length)
            console.log("已经得到的商品id大小：>>>>  " + myMap.size)

            if (goods_data.list.length != myMap.size) {
              console.log()
              console.log("此时可能出现了重复的商品！！！！！！！！！！！！！！！！！！！！！！！！")
              console.log("此时可能出现了重复的商品！！！！！！！！！！！！！！！！！！！！！！！！")
              console.log("此时可能出现了重复的商品！！！！！！！！！！！！！！！！！！！！！！！！")
              console.log()
            }




            this.setData({
              goods_data: goods_data,
            })

            wx.removeStorageSync("getDayUpte")

          }
        })
      ///////////////////////////////////////////


    }else{
      wx.removeStorageSync("getDayUpte")
    }
  },

  //商品图片适配
  imageLoad: function (e) {
    var windowWidth = this.data.windowWidth;
    //淘淘领列表查询图片宽高：589 855
    var $width = e.detail.width;
    //var $height = e.detail.height;
    //var ratio = $width / $height; 
    //设置图片显示宽度,适配0.92的比例，
    var viewWidth = windowWidth;
    var viewHeight = viewWidth;    //计算的高度值     
    this.setData({
      imgwidth: viewWidth,
      imgheight: viewHeight
    })
  },

  //拉到底部刷新
  onPullDownRefresh() {
    console.info('onPullDownRefresh')
    if (this.data.goods_data.paginate.hasNext == false){
      console.log("商品全部查询完毕")
      //拉到底部显示
      this.setData({ loade: false })
    }

    if (!this.data.goods_data.paginate.hasNext) return
    this.getDayUpte()
  },


  //每日推荐
  getGoodDaily: function (e) {

    var that = this
    let data = {
      service: 'psGoods.smallprogram.freeGetGoodsActivityHomeListPageFind',
      params: '{}',
      url_type: 'goods',
      app_token: app.globalData.app_token,
      security_code: app.globalData.security_code
    }

    api.reqData({
      data,
      success: (res) => {

        console.log("--------------每日推荐------------------------------------")
        console.log(res)



        var docList = res.data.data.doc_url
        var itemList = res.data.data.list
        if (itemList.length > 0) {
          this.setData({
            goodDaily: itemList[0]
          })
        }


        /*         var doc_url_key = Object.keys(docList)
                for (var i = 0; i < itemList.length; i++) {
                  JSON.parse(itemList[i].pic_info)
                  var path_id = JSON.parse(itemList[i].pic_info)[0].path_id
                  if (path_id != '') {
                    for (var e = 0; e < doc_url_key.length; e++) {
                      if (path_id === doc_url_key[e]) {
                        itemList[i].pic_src = docList[doc_url_key[e]].replace("https", "http")
                      }
                    }
                  } else {
                    itemList[i].pic_src = ''
                  }
                }
        
                if (res.data.rsp_code == 'succ' && res.data.data.list.length > 0) {
                  this.setData({
                    goodDaily: itemList[0]
                  })
                } */

      }

    })
  },


  //每日推荐列表
  getGoodDailyList: function (e) {
    if (this.data.goodDaily != null) {
      wx.navigateTo({
        url: `../index/gooddaily/list`,
      });
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '等待推荐中...',
        showCancel: false,
      })
    }
  },



  //查看零钱
  lookgold: function () {
    this.setData({
      goldisMasked: false
    })
    wx.navigateTo({
      url: `/pages/my/cash/cash`,
    });
  },

  //新品预告
  getNewProduct: function (e) {

    let data = {
      service: 'psGoods.smallprogram.freeGetGoodsPreSaleListPageFind',
      params: '{}',
      page: '{"page_size":"10","page_no":"1"}',
      url_type: 'goods',
      app_token: app.globalData.app_token,
      security_code: app.globalData.security_code
    }

    api.reqData({
      data,
      success: (res) => {


        console.log("--------------新品预告------------------------------------")
        console.log(res)
        var itemList = res.data.data.list


        if (itemList.length > 0) {
          this.setData({
            goodsPreSale: itemList[0]
          })
        }


        /*         if (res.data.rsp_code == 'succ' && res.data.data.list.length > 0) {
                  if (itemList[0].pic_info_url != null) {
                    itemList[0].pic_info_url = itemList[0].pic_info_url.replace("https", "http");
                  }
                  this.setData({
                    goodsPreSale: itemList[0]
                  })
                } */

      }

    })
  },

  //新品预告列表
  getNewProductList: function (e) {
    if (this.data.goodsPreSale != null) {
      wx.navigateTo({
        url: `../index/newProduct/list`,
      });
    } else {
      wx.showModal({
        title: '温馨提示',
        content: '等待上新中...',
        showCancel: false,
      })
    }


  },


//得到红包
  getgold:function (e) {
            const that = this
            console.log("领取红包")
            const paramsData = {
              detail_id: this.data.detail_id,//红包ID
              member_type_key: 'consumer',//交易方式
              member_id: app.globalData.memberInfo.member_id//会员ID
            }
            let data = {
              service: 'gcActivity.consumer.gcActivityDetailOpen',
              params: JSON.stringify(paramsData),
              url_type: 'goods',
              app_token: app.globalData.app_token,
              security_code: app.globalData.security_code
            }
            console.log(data)
            api.reqData({
              data,
              success: (res) => {
                console.log(res.data)
                console.log(res)
                if (res.data.rsp_code === "succ") {
                  that.setData(
                    {
                      alertpack:false,
                      goldisMasked: true
                    }
                  );
                }
              }
            })
  },

  //弹出红包
  alertred: function (e) {
      const that = this
      console.log("创建红包访问接口参数")
      let gift_value = (['0.05', '0.06', '0.07', '0.08', '0.09', '0.10'][Math.floor(Math.random() * 6)]);
      console.log(app.globalData.memberInfo)
      //创建红包访问接口参数
      const paramsData = {
        to_member_id: app.globalData.memberInfo.member_id,
        to_member_type_key: 'consumer',
        to_member_info: app.globalData.memberInfo.mobile,
        gift_value: gift_value,
        remark: '红包'
      }
      let data = {
        service: 'gcActivity.consumer.gcActivityDetailCreate',
        params: JSON.stringify(paramsData),
        url_type: 'goods',
        app_token: app.globalData.app_token,
        security_code: app.globalData.security_code
      }
      console.log(data)
      api.reqData({
        data,
        success: (res) => {
          console.log(res)
          if (res.data.rsp_code == "succ") {
            that.setData(
              {
                gift: gift_value,
                gift_type: '元',
                detail_id: res.data.data.detail_id,
                alertpack: true
              }
            );
          }else{
            that.setData(
              {
                alertpack: false
              }
            );
          }
        }
      })
  },




  //每日签到
  getQianDao: function (e) {
    const that = this

    if (app.globalData.hasLogin === false) {//没有登录
      wx.showModal({
        title: '温馨提示',
        content: '您还没有登录，是否要登录？',
        showCancel: true,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
    } else {//已经登录

      let paramsData = {
        consumer_id: app.globalData.memberInfo.member_id,
      }

      let data = {

        service: 'consumer.consumer.consumerSign',
        params: JSON.stringify(paramsData),
        url_type: 'member',
        app_token: app.globalData.app_token,
        security_code: app.globalData.security_code
      }


      api.reqData({
        data,
        success: (res) => {
          console.log(res.data)
          if (res.data.rsp_code === "succ") {
            that.setData(
              {
                isMasked: true,
                signContent: res.data.data.title
              }
            );
          }
        }
      })
    }
  },

  hideBackground: function (e) {
    this.setData(
      {
        isMasked: false,
        alertpack: false,
        goldisMasked: false,
      }
    );
  },



  //淘淘领
  taotaoling: function (e) {
    wx.navigateTo({
      url: `/pages/buy/goodslist/goodslist`,
    });
    // wx.showModal({
    //   title: '提示',
    //   content: '【淘系】商品春节期间，暂停下单！',
    //   showCancel:false,
    // })
  },
  //会过
  huiguo: function (e) {
    wx.navigateTo({
      url: `/pages/buy/huiguolist/huiguolist`,
    });
  },



//自营

  ziying: function (e) {
    wx.navigateTo({
      url: `/pages/buy/ownlist/ownlist`,
    });
  },





  //会员
  // huiyuan: function (e) {
  //   const ds = e.currentTarget.dataset;
  //   wx.showModal({
  //     title: '温馨提示',
  //     content: '暂无此功能',
  //     showCancel: false,
  //     success: function (res) {
  //       if (res.confirm) {
  //         console.log('用户点击确定')
  //       } else {
  //         console.log('用户点击取消')
  //       }
  //     }
  //   })

  // },



  //新人专享
  getNewPeopleList: function (e) {
    // wx.navigateTo({
    //   url: `../index/newpeople/list`,                 // 暂时停止新人专享
    // });
  },

  //搜索页面
  sousuo: function (e) {
    wx.navigateTo({

      url: `../../pages/index/sousuo/list`,
    });
  },

  // banner
  listClick: function (event) {

    var url = event.currentTarget.url

    var url = event.currentTarget.dataset.url
    console.log("LLLLLLLLLLLLLLLLLL")
    console.log('/pages/banner/banner?url=' + url)
    wx.navigateTo({ url: "/pages/banner/banner?url=" + url })

  },

  //banner 图列表
  gdAppAdvertFind: function (e) {
    const data = {
      service: 'gdAppAdvert.app.gdAppAdvertFind',
      params: '{"category":"c_app_home"}',
      url_type: 'goods',
      app_token: app.globalData.app_token,
      security_code: app.globalData.security_code

    }

    api.reqData({
      data,
      success: (res) => {

        console.log("--------------首页轮播图------------------------------------")
        console.log(res);

        var docList = res.data.data.doc_url
        var itemList = res.data.data.list


        var doc_url_key = Object.keys(docList)
        for (var i = 0; i < itemList.length; i++) {

          var path_id = itemList[i].path_id;

          if (path_id != '') {
            for (var e = 0; e < doc_url_key.length; e++) {
              if (path_id === doc_url_key[e]) {
                itemList[i].pic_info = docList[doc_url_key[e]].replace("https", "http");
              }
            }
          } else {
            itemList[i].pic_info = ''
          }
          console.log(itemList[i].url)
          itemList[i].url = itemList[i].url.replace("=", "%3D");
          itemList[i].url = itemList[i].url.replace("?", "%3F");
          itemList[i].url = itemList[i].url.replace("&", "%26");
          itemList[i].url = itemList[i].url.replace("=", "%3D");
          itemList[i].url = itemList[i].url.replace("http", "https");
          itemList[i].url = itemList[i].url.replace("httpss", "https");
        }



        this.setData({
          carousels: itemList
        })
      },
    })

  },


  /*   getEveryday: function (e) {
      const data = {
        service: 'gdAppAdvert.app.gdAppAdvertFind',
        params: '{"category":"c_app_home"}',
        url_type: 'goods',
      }
    }, */


  onReachBottom() {
    console.info('onReachBottom>>>' + this.data.goods_data.paginate.hasNext)
    if (this.data.goods_data.paginate.hasNext == undefined){
      this.getDayUpte();
    } else if (this.data.goods_data.paginate.hasNext){
      this.getDayUpte();
    } else{
      console.log("商品全部查询完毕")
      return
    }
  },



//返回顶部
  goTopFun: function (e) {
    wx.pageScrollTo({
      scrollTop: 0
    }),
      this.setData({
        'goTop_show': false
      });
  },
  scrollTopFun: function (e) {
    if (e.detail.scrollTop > 100) {//触发gotop的显示条件  
      this.setData({
        'goTop_show': true
      });
    }
  },


  onReady() {

  }

})
